import json
import os
import matplotlib.pyplot as plot
from PIL import Image

path = '../../resources/'
result_path = path + 'result/'
trend_path = path + 'result_trend/'


def merge_gif():
    result = os.listdir(trend_path)
    for i in result:
        # 隐藏文件
        if i.startswith('.'):
            continue
        gif_frames = []
        imgs = os.listdir(trend_path + i)
        for j in imgs:
            if not j.endswith('.jpg'):
                continue
            img = Image.open(trend_path + i + '/' + j)
            gif_frames.append(img)
        gif_frames[0].save(trend_path + i + '/' + i + '.gif', save_all=True, append_images=gif_frames[1:], loop=0,
                           duration=200)
        print(i + 'gif保存成功')


def save_trend():
    result = os.listdir(result_path)
    result.sort()
    objs = []
    exists = os.listdir(trend_path + '第一层')
    for i in result:
        # 非json文件不要
        if not i.endswith('.json'):
            continue
        # 已经存在的不要
        name = i[:14]
        if name + '.jpg' in exists:
            continue
        with open(result_path + i, 'r') as file:
            try:
                obj = json.loads(file.readline())
            except UnicodeError:
                print(i)
            obj['name'] = name
            objs.append(obj)
        file.close()
    for o in objs:
        figure = plot.figure(dpi=150)
        plot.plot(o['wights'][0])
        figure.savefig(trend_path + '第一层/%s.jpg' % o['name'])
        plot.plot(o['wights'][1])
        figure.savefig(trend_path + '第二层/%s.jpg' % o['name'])
        plot.plot(o['wights'][2])
        figure.savefig(trend_path + '第三层/%s.jpg' % o['name'])
        print(o['name'] + '结果保存完成')
    merge_gif()


save_trend()
